<template>
  <view style="position: relative;">
    <view v-if="myUserId != ''" class="readAllMessage-wrapper">
      <image @tap="readAllMessage" class="readAllMessage"
             src="https://www.douluodalu.icu:9000/school/static/read_all.png"></image>
    </view>
    <u-sticky offset-top="10">
      <view class="head-wrapper">
        <!--    头部导航标签-->
        <u-tabs
            :current="tagIndex"
            @click="toScroll"
            :list="list4"
            lineWidth="20"
            lineHeight="7"
            :activeStyle="{
        color: '#4ea4f9',
        fontWeight: 'bold',
        transform: 'scale(1.05)'
    }"
            :inactiveStyle="{
        color: '#303133',
        transform: 'scale(1)',
        fontWeight: '540'
    }"
            itemStyle="padding-left: 40px; padding-right: 40px; height: 34px;"
        >
        </u-tabs>
      </view>
    </u-sticky>
    <!--滚动列表内容-->
    <view v-if="isLogin">
      <swiper :current="tagIndex" class="swiper" :circular="false" @change="swiperChange" swiperDuration="250">
        <!--      左右滑动菜单子项-->
        <swiper-item>
          <u-empty v-if="showEmptyNotification"
                   mode="message"
                   icon="https://cdn.uviewui.com/uview/empty/message.png">
          </u-empty>
          <scroll-view @scrolltolower="notificationScrolltolower" v-else scroll-y style="height: 100vh">
            <view @click="openPopup" style="display: flex;align-items: center">
              <image :src="messageType[notifyIndex].url" style="width: 25px;height: 25px;padding: 10px"></image>
              <up-text bold size="14" suffixIcon="arrow-down"
                       iconStyle="font-weight:bold;font-size: 16px;padding-left: 5px;color:black"
                       :text="messageType[notifyIndex].name"></up-text>
            </view>
            <u-line></u-line>
            <u-empty v-if="showEmptyReplyAndLike"
                     mode="message"
                     icon="https://cdn.uviewui.com/uview/empty/message.png">
            </u-empty>
            <view
                @longtap.stop="handleRemove(item, index)"
                v-for="(item, index) in notificationList"
                :key="index">
              <view @tap="readNotification(item,index)"
                    class="notification-wrapper">
                <view class="notification-left">
                  <u-avatar
                      shape="circle"
                      size="45"
                      :src="item.avatar"
                      customStyle="margin: -3px 5px -3px 0"
                  ></u-avatar>
                  <view style="font-size: 12px;padding: 0 0.5rem;width: 65vw;">
                    <view style="display: flex;align-items: center;justify-content: space-between;width: inherit;">
                      <view style="display: flex;align-items: center;">
                        <text>@{{ item.userName }}&nbsp;</text>
                        <text class="operation">{{ item.type == 'reply' ? '回复：' : '赞了你的' }}</text>
                      </view>
                      <text v-if="item?.type == 'reply'" class="reply">回复</text>
                    </view>

                    <view class="operation-content">
                      <view v-if="item.type == 'like'" class="like">
                        <image :src="item.readStatus == 'read'
                        ? 'https://www.douluodalu.icu:9000/school/static/like.png' :
                        'https://www.douluodalu.icu:9000/school/static/like_active.png'"></image>
                        <text :style="{color: item.readStatus == 'read' ? 'rgba(0, 0, 0, 0.63)' : '#4ea4f9'}">+1</text>
                      </view>
                      <view v-else class="like">
                        <text :style="{color: item.readStatus == 'read' ? 'rgb(192,192,192)' : '#4ea4f9'}"
                              class="reply-content u-line-1">
                          {{
                            item?.replyImages == undefined || item?.replyImages == "" ? item?.replyContent : '[图片]'
                          }}
                        </text>
                      </view>
                      <text style="color: rgb(192,192,192)">{{ formatTimeAgo(item.createdTime) }}</text>
                    </view>
                  </view>
                </view>

                <image class="source-image" v-if="item?.sourceImages != '' && item?.sourceImages !== undefined "
                       :src="item?.sourceImages"
                       style=""></image>
                <view class="source-content u-line-3" v-else>{{ item?.sourceContent }}</view>
              </view>
              <view style="padding-left:65px;padding-right: 10px">
                <u-line></u-line>
              </view>
            </view>
            <view style="height: 60px;"></view>

          </scroll-view>

        </swiper-item>
        <swiper-item>
          <chat-list-skeleton v-if="chatListLoading"></chat-list-skeleton>
          <scroll-view scroll-y v-else
                       @scrolltolower="scrolltolower"
                       :refresher-threshold="100"
                       style="height: 100vh">
            <u-line></u-line>
            <view v-if="indexList?.length > 0"
                  style=""
                  v-for="(item, index) in indexList"
                  @tap.stop="readMessage(index)"
                  :key="index">
              <!--              :url="`/pages/msg/chat1?userId=${item.userId == myUserId ? item.friendId : item.userId}`"-->
              <navigator
                  :url="`/pages/msg/chat1?userId=${item.userId == myUserId ? item.friendId : item.userId}`"
                  style="position: relative!important;;padding: 30rpx;display: flex;align-items: center;justify-content: space-between">
                <view style=" display: flex;align-items: center;width: 100%; ">
                  <u-avatar
                      shape="circle"
                      size="50"
                      mode="contain"
                      :src="item.friendAvatar"
                      customStyle="margin: -3px 5px -3px 0"
                  ></u-avatar>&nbsp;
                  <view style="font-size: 12px; width: 100%;">
                    <view style="display: flex;align-items: center;justify-content: space-between;width: inherit;">
                      <text>{{ item.friendName }}</text>
                      <text>{{ formatTimeAgo(item.lastMessageTime) }}</text>
                    </view>
                    <view class="content-container">
                      <view class="content-wrapper">
                        <view v-if="item.messageType == 'text'" class="u-line-1">
                          {{ item.lastMessage }}
                        </view>
                        <view v-if="item.messageType == 'image'" class="content">分享[图片]
                        </view>
                        <view v-if="item.messageType == 'video'" class="content">分享[视频]
                        </view>

                        <view v-if="item.unreadNumber != 0" class="unreadNumber">
                          {{ item.unreadNumber }}
                        </view>
                      </view>
                    </view>
                  </view>
                </view>
              </navigator>
            </view>
            <u-empty v-else
                     mode="message"
                     icon="https://cdn.uviewui.com/uview/empty/message.png"
            >
            </u-empty>
            <view style="height: 70rpx;"></view>
          </scroll-view>
        </swiper-item>
      </swiper>
    </view>
    <view v-else class="content">
      <swiper :current="tagIndex" class="swiper" :circular="false" @change="swiperChange" swiperDuration="250">
        <!--      左右滑动菜单子项-->
        <swiper-item>
          <navigator url="/pages/my/login">
            <view class="unlogin_content">
              <image style="margin: 4rem 0 0 2.5rem"
                     src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
              <text style="text-align: center">登录解锁更多有趣内容</text>
            </view>
          </navigator>
        </swiper-item>
        <swiper-item>
          <navigator url="/pages/my/login">
            <view class="unlogin_content">
              <image style="margin: 4rem 0 0 2.5rem"
                     src="https://www.douluodalu.icu:9000/school/static/empty.png"></image>
              <text style="text-align: center">登录解锁更多有趣内容</text>
            </view>
          </navigator>
        </swiper-item>
      </swiper>
    </view>

    <!--  底部淡出层列表-->
    <u-popup :round="10" :show="show" mode="bottom" @close="close" @open="open">

      <view style="border-bottom: 1px solid rgba(138,138,138,0.05);padding: 5px" v-for="(item,index) in messageType"
            :key="item.type" @click="notifyChoose(index)">
        <view style="display: flex;align-items: center;justify-content: space-between">
          <view style="display: flex;align-items: center;">
            <image :src="item.url" style="width: 25px;height: 25px;padding: 10px" @click="close"></image>
            <text style="color: black;font-size: 14px;font-weight: 530">{{ item.name }}</text>
          </view>
          <image src="https://www.douluodalu.icu:9000/school/static/gou.png" style="height: 20px;width: 20px;"
                 v-show="notifyIndex === index"></image>
        </view>
      </view>
      <view @click="show=false" style="height: 50px;display: flex;align-items: center;
    justify-content: center;border: none;outline: none;font-weight: bold;font-size: 16px;
    background-color: rgba(138,138,138,0.05);color: rgba(0,0,0,0.5);">
        关闭
      </view>
    </u-popup>
    <u-overlay :show="showRemove" @click="showRemove=false">
      <view style="width: 100%;height: 100vh;display: flex;align-items: center;justify-content: center">
        <view class="slot-content" style="background-color: white;line-height: 50px;
      border-radius: 5px;width: 70vw;height: 16vh;display: flex;
      justify-content: flex-start;flex-direction: column">
          <text style="color: #4ea4f9;font-weight: 550;font-size: 18px;padding-left: 15px">提醒</text>
          <u-gap height="2" :bg-color="'#4ea4f9'"></u-gap>
          <text style="padding-left: 15px" @tap.stop="deleteNotification">删除</text>
        </view>

      </view>
    </u-overlay>

  </view>
  <tabbar></tabbar>

</template>

<script>
import Blog from "@/components/Blog.vue";
import tabbar from "@/components/tabbar/tabbar.vue";
import {
  getToken,
  getUserId,
} from "@/utils/auth";
import {formatLocation, formatTimeAgo} from "@/utils/format";
import {getChatList, readAllMessage, readMessage} from "@/api/chat";
import ChatListSkeleton from "@/components/skeleton/ChatListSkeleton.vue";
import useUserStore from "@/store/user";
import {logout} from "@/utils/api";
import {deleteNotification, getNotificationList, readNotification} from "@/api/notification";
import {locateComment, removeCommentById} from "@/api/comment";

export default {
  components: {ChatListSkeleton, Blog, tabbar},
  data() {
    return {
      showSkeleton: false,
      showEmptyNotification: false,
      showEmptyReplyAndLike: false,
      showRemove: false,
      removeItem: {},
      removeActionList: [{
        name: '删除',
      }],
      removing: false,
      pageSize: 15,
      notificationCurrent: 1,
      notificationTotal: 0,
      notificationPageSize: 20,
      notificationList: [],
      filterList: [],
      current: 1,
      chatListLoading: true,
      noMessage: false,
      show: false,
      isLogin: false,
      indexList: [],
      notifyIndex: 0,
      messageType: [
        {type: 1, name: '全部消息', url: 'https://www.douluodalu.icu:9000/school/static/all_msg.png'},
        {type: 2, name: '回复我的', url: 'https://www.douluodalu.icu:9000/school/static/all_reply.png'},
        {type: 3, name: '点赞', url: 'https://www.douluodalu.icu:9000/school/static/all_like.png'}
      ],
      urls: [
        'https://cdn.uviewui.com/uview/album/1.jpg',
        'https://cdn.uviewui.com/uview/album/2.jpg',
        'https://cdn.uviewui.com/uview/album/3.jpg',
        'https://cdn.uviewui.com/uview/album/4.jpg',
        'https://cdn.uviewui.com/uview/album/5.jpg',
        'https://cdn.uviewui.com/uview/album/6.jpg',
        'https://cdn.uviewui.com/uview/album/7.jpg',
        'https://cdn.uviewui.com/uview/album/8.jpg',
        'https://cdn.uviewui.com/uview/album/9.jpg',
        'https://cdn.uviewui.com/uview/album/10.jpg',
      ],
      myUserId: '',
      trigger: false,

      tagIndex: 0,
      lineBg: "",
      list4: [
        {name: '提醒'},
        {name: '私信',}],
    };
  },
  onShow() {
    let token = getToken();
    if (token !== null && token !== '' && token !== undefined) {
      // uni.$on('websocketMessage', (res) => {
      //   if (res != null) {
      //     let receivedData = JSON.parse(res)
      //     if (receivedData?.fromUserId !== undefined) {
      //       let receivedMessage = {
      //         content: receivedData.content,
      //         readStatus: receivedData.readStatus,
      //         fromUserId: receivedData.fromUserId,
      //         toUserId: receivedData.toUserId,
      //         messageType: receivedData.messageType,
      //         id: receivedData.id,
      //         sendTime: receivedData.sendTime,
      //       }
      //       if(this.chatInfo?.chatList === undefined){
      //         this.chatInfo.chatList = []
      //         this.chatInfo.chatList.push(receivedMessage);
      //       }else {
      //         this.chatInfo.chatList.push(receivedMessage);
      //
      //       }
      //       this.readMessage(receivedMessage.fromUserId, receivedMessage.toUserId)
      //     }
      //
      //   }
      //   // this.textareaFocus = true
      //
      //   // console.log(res)
      // })

      this.isLogin = true
      this.getChatList()
      this.getNotificationList()
    }

  },
  onLoad() {
    let token = getToken();
    if (token !== null && token != '' && token !== undefined) {
      this.myUserId = getUserId()
    } else {
      uni.navigateTo({
        url: '/pages/my/login',
      })
    }
  },
  methods: {
    handleRemove(item, index) {
      this.removing = true
      this.showRemove = true
      this.removeItem.id = item.id
      this.removeItem.index = index
    },
    async deleteNotification() {
      await deleteNotification(this.removeItem.id)
      this.notificationList.splice(this.removeItem.index, 1)
      this.removing = false
      this.showRemove = false
    },
    readMessage(index) {
      this.indexList[index].unreadNumber = 0
    },
    async readNotification(item, index) {
      if (!this.removing) {
        if (item.type == 'reply') {
          const read = await readNotification(item.id)
          const res = await locateComment(item.commentId)
          if (res.code == '200' && res.data?.url !== undefined) {
            if (res.data.url == 'index') {
              uni.navigateTo({
                url: `/pages/comment/indexPage?id=${item.postId}&commentId=${item.commentId}`
              })
            }
            if (res.data.url == 'reply') {
              uni.navigateTo({
                url: `/pages/comment/replyPage?id=${res.data?.comment?.rootCommentId}&commentId=${item?.commentId}`
              })
            }
          } else {
            uni.showToast({
              title: res?.data !== undefined ? res.data : '评论不存在',
              icon: 'none'
            })
            await deleteNotification(item.id)
            this.notificationList.splice(index, 1)
          }
        }
        if (item.type == 'like') {
          uni.navigateTo({
            url: `/pages/comment/LikeUser?id=${item.id}`
          })
        }
        useUserStore().setUnreadMessageNumber(useUserStore().unreadMessageNumber - 1)
      }

    },
    getChatList() {
      getChatList(this.pageSize, this.current).then((res) => {
        if (res.data?.length == 0 || res.data == '暂无消息') {
          this.noMessage = true
        } else {
          this.indexList = res.data
        }
        this.chatListLoading = false
      })
      // }
    },
    getNotificationList() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      getNotificationList(this.notificationPageSize, this.notificationCurrent).then((res) => {
        this.notificationList = res.data.records
        this.filterList = res.data.records
        this.notificationTotal = res.data.total
        this.showEmptyNotification = this.notificationList?.length === 0
      })
    },
    OnRefresh() {
      this.trigger = true
      this.current = 1
      getChatList(this.pageSize, this.current).then((res) => {
        this.indexList = res.data
        this.chatListLoading = false
        this.trigger = false
      })
    },
    async readAllMessage() {
      let token = getToken();
      if (!(token !== null && token !== '' && token !== undefined)) {
        uni.showToast({
          title: '请先登录',
          icon: 'none'
        })
        setTimeout(() => {
          uni.navigateTo({url: '/pages/my/login'})
        }, 500)
        return;
      }
      let _this = this
      uni.showModal({
        title: '确定全部标记为已读吗?',
        cancelText: '取消',
        confirmText: '确定',
        confirmColor: '#4ea4f9',
        async success(res) {
          if (res.confirm) {
            const res = await readAllMessage()
            let unreadMessageNumber = Number(useUserStore().unreadMessageNumber);
            let readAllMessages = Number(res.data);
            let num = Number(unreadMessageNumber - readAllMessages)
            num = num < 0 ? 0 : num
            useUserStore().setUnreadMessageNumber(num)
            _this.indexList.forEach((item) => {
              item.unreadNumber = 0
            })
            _this.notificationList.forEach((item) => {
              item.readStatus = 'read'
            })
          } else if (res.cancel) {

          }
        }
      })

    },
    formatTimeAgo,
    swiperChange(event) {

      this.tagIndex = event.detail.current
    },
    notifyChoose(index) {
      this.notifyIndex = index
      this.show = false
      if (index == 1) {
        this.notificationList = this.filterList.filter((item) => item.type == 'reply');
        this.showEmptyReplyAndLike = this.notificationList?.length == 0
      } else if (index == 2) {
        this.notificationList = this.filterList.filter((item) => item.type == 'like')
        this.showEmptyReplyAndLike = this.notificationList?.length == 0
      } else {
        this.showEmptyReplyAndLike = false
        this.notificationList = this.filterList
      }
    },
    openPopup(popupData) {
      this.popupData = popupData
      uni.$u.sleep().then(() => {
        this.show = !this.show
      })
    },
    open() {
      // console.log('open');
    },
    close() {
      this.show = false
      // console.log('close');
    },
    scrolltolower() {
      this.current++
      getChatList(this.pageSize, this.current * 10).then((res) => {
        this.indexList = [...this.indexList, ...res.data]
        this.chatListLoading = false
      })
    },
    async notificationScrolltolower() {
      if(this.filterList?.length < this.notificationTotal){
        this.notificationCurrent++
        const res = await getNotificationList(this.notificationPageSize, this.notificationCurrent)
        this.notificationList = [...this.notificationList, ...res.data.records]
        this.filterList = [...this.filterList, ...res.data.records]
        this.chatListLoading = false
      }else {
        uni.showToast({icon: 'none', title: '到底了~', position: 'bottom'})
      }

    },
    loadmore() {
      // console.log("加载更多")
    },
    toSearch() {
      uni.navigateTo({url: '/pages/search/search'})
    },
    toTopic() {
      uni.navigateTo({url: '/pages/topic/AllTopic'})
    },
    toScroll(event) {
      this.tagIndex = event.index
    },
  },
  created() {
  },
};
</script>

<style>

.head-wrapper {
  display: flex;
  justify-content: space-around;
  align-items: center;
}


.swiper {
  height: calc(100vh - 120rpx);
}

.notification-wrapper {
  padding: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between
}

.notification-left {
  display: flex;
  align-items: flex-start;
}

.operation {
  color: rgb(192, 192, 192)
}

.operation-content {
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
}

.like {
  display: flex;
  align-items: center;
  padding: 5px 0
}

.like image {
  width: 20px;
  height: 20px;
}

.like text {
  color: #4ea4f9
}

.reply {
  background-color: rgba(192, 192, 192, 0.74);
  border-radius: 5rpx;
  padding: 1px 5px;
  color: rgba(0, 0, 0, 0.63)
}

.reply-content {
  color: #000
}


.notification-left {
  display: flex;
  align-items: center
}

.source-image {
  width: 50px;
  height: 50px;
  border-radius: 5px;
}

.source-content {
  width: 50px;
  height: 50px;
  max-width: 50px;
  max-height: 50px;
  background-color: rgba(192, 192, 192, 0.46);
  color: rgba(110, 109, 109, 0.59);
  font-size: 12px;
  border-radius: 5px;
  text-align: center;
}

.unlogin_content {
  display: flex;
  justify-content: center;
  flex-direction: column;
  font-size: 14px;
  color: #b0b0b0;
}

.content-container {
  display: flex;
  flex-direction: column
}

.content-wrapper {
  display: flex;
  align-items: center;
  padding: 5px 0;
  color: #504f4f;
}

.unreadNumber {
  background-color: #f51616;
  display: flex;
  align-items: center;
  color: white;
  width: 5px;
  right: 25px;
  top: 29px;
  height: 5px;
  border-radius: 50%;
  justify-content: center;
  padding: 7px;
  position: absolute;
}


.content {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  width: 100%;
}

.readAllMessage-wrapper {

  position: absolute;
  right: 1rem;
  bottom: 3rem;
  z-index: 100;
  background-color: white;
  padding: 0.5rem;
  scale: 0.7;
  border: 1px solid rgba(154, 154, 154, 0.3);
  border-radius: 10px;

}

.readAllMessage {
  width: 2rem;
  height: 2rem;

}


</style>
